sidebar侧边栏

vuepress支持两种方式的侧边栏

  1. 所有页面会使用相同的侧边栏
  2. 不同子路径下的页面会使用不同的侧边栏

自动生成侧边栏

使用依赖directory-tree - npm (npmjs.com)open in new window

npm i directory-tree

所有页面相同侧边栏

docs\.vuepress\autoSiderbar\AllPageSameSildeBar.js

/**
 * 所有页面会使用相同的侧边栏
 */

const path = require("path");
const dirTree = require("directory-tree");
const titles = require('./textTitle');
const SRC_PATH = path.resolve(__dirname, "../../");
var fs = require('fs');


/**
 * 默认使用文件夹名称作为route,如果文件有中文则sidebar不会生效
 * 维护了一个份textTitle来将route转换为title
 */
function getTitle(name){
  if(titles[name] === undefined){
    console.log("===================================================================");
    console.warn("[Warn]: 请在textTitle.js 文件中维护一个 %s 的title",'vuepress1');
    console.log("===================================================================");
    return name;
  }
  return titles[name];
}

function toSidebarOption(tree = []) {
  if (!Array.isArray(tree)) return [];


  return tree.map((v) => {
    var stat = fs.statSync(v.path);

    if (stat.isDirectory()) {
      return {
        text: getTitle(v.name),
        // link: v.path.split("docs")[1]+'/',
        link: `/${v.name}/`,
        children: toSidebarOption(v.children),
      };
    } else {
      return {
        text: path.basename(v.path).replace(/\.md$/, ""),
        link: v.path.split("docs")[1]
      }
    }
  });
}

/**
 去除.vuepress的节点
 {
            "path":"d:/Github/vlog/docs/.vuepress",
            "name":".vuepress",
            "children":Array[4]
 }
 * @param {*} srcDir 
 * @returns 
 */
function removeDotvuepress(srcDir){
    return srcDir.children.filter(node => !node.path.endsWith('.vuepress') );
}

function autoGetSidebarOptionBySrcDir(srcPath = SRC_PATH) {
  const srcDir = dirTree(srcPath, {
    extensions: /\.md$/,
    normalizePath: true,
    exclude: /README.md|readme.md/
  });

  const children = removeDotvuepress(srcDir);
  //console.log(JSON.stringify(children))

  const sideBar = toSidebarOption(children);
  console.log('Generated sidebar finished :)');
  return sideBar;
}

//=================测试===============================
//const result = autoGetSidebarOptionBySrcDir();
//console.log(JSON.stringify(result));

/** 生成的结果
[
    {
        "text":"Vuepress博客搭建",
        "link":"/vuepress/",
        "children":[
            {
                "text":"01 搭建vuepress2",
                "link":"/vuepress/01 搭建vuepress2.md"
            },
            {
                "text":"02 图片存放路径",
                "link":"/vuepress/02 图片存放路径.md"
            },
            {
                "text":"03 侧边栏配置",
                "link":"/vuepress/03 侧边栏配置.md"
            }
        ]
    }
]
 */

module.exports = autoGetSidebarOptionBySrcDir;

不同子路径不同侧边栏⭐

docs\.vuepress\autoSiderbar\DiffRouteDifSidebar.js

/**
 * 不同子路径下的页面会使用不同的侧边栏
 */

const autoGetSidebarOptionBySrcDir = require('./AllPageSameSildeBar');

function autoGenSidebar(){
    let result = {};
    const contents = autoGetSidebarOptionBySrcDir();
    contents.forEach(element => {

        if(!(element.link in result)){
            result[element.link] = []
        }

        result[element.link].push({
            text: element.text,
            children: element.children
        })
    });

    return result;
}

// 测试
//console.log(JSON.stringify(autoGenSidebar()));
/**
{
    "/vuepress/":[
        {
            "text":"Vuepress博客搭建",
            "children":[
                {
                    "text":"01 搭建vuepress2",
                    "link":"/vuepress/01 搭建vuepress2.md"
                },
                {
                    "text":"02 图片存放路径",
                    "link":"/vuepress/02 图片存放路径.md"
                },
                {
                    "text":"03 侧边栏配置",
                    "link":"/vuepress/03 侧边栏配置.md"
                }
            ]
        }
    ]
}
*/

 module.exports = autoGenSidebar;

Title维护😁

docs\.vuepress\autoSiderbar\textTitle.js

/**
 * 本来的想法是使用文件夹的名称来作为sidebar的route
 * 但是发现route不能使用中文
 * 所以将文件夹的名称的作为route的情况下,route对应的text则在这里维护一份
 * 
 * key: route
 * val: text
 */

const titles = {
    'vuepress': 'Vuepress博客搭建'
};


module.exports = titles;

配置

配置自动生成的侧边栏

const autoGenSidebar = require('./autoSiderbar/DiffRouteDifSidebar')
const sidebar = autoGenSidebar();

module.exports = {
  lang: 'zh-CN',
  title: 'Aeroxian的Vlog',
  description: 'Aeroxian的Vuepress Blog',
  head: [['link', { rel: 'icon', href: '../.vuepress/public/images/favicon-32x32.png' }]], // icon设置

  themeConfig: {
    logo: '../.vuepress/public/images/logo.png',
    lastUpdated: false,   // 禁用显示更新时间
    contributors: false,   // 禁用显示贡献者
    sidebar
  },
}

参考

配置 | VuePress (vuejs.org)open in new window